/*
 * @Description: 
 * @Version: 1.0
 * @Autor: lzc
 * @Date: 2022-05-31 15:14:15
 * @LastEditors: lzc
 * @LastEditTime: 2022-08-12 14:11:15
 */
#include "nvs.h"
#include "pan_main.h"
#include "esp_log.h"

esp_err_t user_nvs_save_blob(const char *key, const void *value, size_t length)
{
    nvs_handle my_handle;
    esp_err_t err;

    // Open
    err = nvs_open(STORAGE_NAMESPACE, NVS_READWRITE, &my_handle);
    if (err != ESP_OK)
        return err;

    // Write
    err = nvs_set_blob(my_handle, key, value, length);
    if (err != ESP_OK)
        return err;

    // Commit written value.
    // After setting any values, nvs_commit() must be called to ensure changes are written
    // to flash storage. Implementations may write to storage at other times,
    // but this is not guaranteed.
    err = nvs_commit(my_handle);
    if (err != ESP_OK)
        return err;
    ESP_LOGI("PAN_NVS", "save_ok");
    // Close
    nvs_close(my_handle);
    return ESP_OK;
}

esp_err_t user_nvs_read_blob(const char *key, void *out_value, size_t *length)
{
    nvs_handle my_handle;
    esp_err_t err;

    // Open
    err = nvs_open(STORAGE_NAMESPACE, NVS_READONLY, &my_handle);
    if (err != ESP_OK)
        return err;

    // Read
    err = nvs_get_blob(my_handle, key, out_value, length);
    if (err != ESP_OK && err != ESP_ERR_NVS_NOT_FOUND)
        return err;

    // Close
    nvs_close(my_handle);
    return ESP_OK;
}